const Vue = require("vue");
const express = require("express"); // node服务器
const fs = require("fs");
const { createBundleRenderer } = require("vue-server-renderer");
const setupDevServer = require("./build/setup-dev.server");
const server = express();
const isProd = process.env.NODE_ENV === "production";
let renderer;
let onReady;
if (isProd) {
  // 获取模版
  const template = fs.readFileSync("./index.template.html", "utf-8");
  // 服务端文件
  const serverBundle = require("./dist/vue-ssr-server-bundle.json");
  // 客户端打包文件
  const clientManifest = require("./dist/vue-ssr-client-manifest.json");
  renderer = createBundleRenderer(serverBundle, {
    template,
    clientManifest,
  });
} else {
  // 开发模式->监视打包构建->重新生成renderer渲染器
  onReady = setupDevServer(server, (serverBundle, template, clientManifest) => {
    renderer = createBundleRenderer(serverBundle, {
      template,
      clientManifest,
    });
  });
}

/**
 * 渲染函数
 * @param {*} req
 * @param {*} res
 */
const render = async (req, res) => {
  try {
    const html = await renderer.renderToString({
      title: "this is demo",
      meta: '<meta name="description" content="borey">',
      url: req.url,
    });
    // 设置相应头防止乱码
    res.setHeader("Content-Type", "text/html;charset=utf8");
    res.end(html);
  } catch (error) {
    res.status(500).end("server error");
  }
};

// const render = (req, res) => {
//   renderer.renderToString({
//     title: 'this is demo',
//     meta: '<meta name="description" content="test">'
//     url: req.url
//   }, (err, html) => {
//     if (err) return res.status(500).end('server error')
//     res.setHeader('Content-Type', 'text/html;charset=utf8')
//     res.end(html)
//   })
// }

// 操作磁盘上的文件
server.use("/dist", express.static("./dist"));

/**
 * 服务器读取
 */
server.get(
  "*", // 服务端路由设置为“*”，意味着所有的路由都会进入这里
  isProd
    ? render
    : async (req, res) => {
        await onReady;
        render(req, res);
      }
);

/**
 * 服务器监听
 */
server.listen(3000, () => {
  console.log("server success");
});
